package com.maoning.product.web;

import com.maoning.product.entity.CategoryEntity;
import com.maoning.product.service.CategoryService;
import com.maoning.product.vo.Catelog2Vo;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.jws.WebParam;
import java.util.List;
import java.util.Map;

/**
 * @Author : 猫宁
 * @Date: 2021/12/13
 */
@Controller
public class IndexController {
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private RedissonClient redisson;

    @GetMapping({"/", "/index.html"})
    public String indexPage(Model model) {
        List<CategoryEntity> list = categoryService.getLevel1Categorys();
        model.addAttribute("categorys", list);
        return "index";
    }

    @ResponseBody
    @GetMapping("/index/json/catalog.json")
    public Map<String, List<Catelog2Vo>> getCatelogJson() {
        Map<String, List<Catelog2Vo>> listMapmap = categoryService.getCatelogJson();
        return listMapmap;
    }

    @ResponseBody
    @GetMapping("/hello")
    public String hello() {
        final RLock lock = redisson.getLock("hellolock");
        try {
            lock.lock();
            //看门狗!
            //1.加上的锁会自动续期(如果业务超长),没写时间的话默认续期30秒.
            //2.加锁的业务如果完成,即使不手动解锁,锁默认30秒后自动删除.
            System.out.println(Thread.currentThread().getId() + "==>拿到了锁,执行代码");
            Thread.sleep(5000);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
            System.out.println(Thread.currentThread().getId() + "==>释放锁");
        }
        return "hello2";
    }

}
